import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './fenzi.less';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Popconfirm, TreeSelect, Tree, message } from 'antd';
import { TableC, SelectC, ModalC, PrimaryC, PrimaryGhostC, InputC, TreeSelectC } from '../../../comps';
const { TreeNode } = Tree;
const { SHOW_PARENT, SHOW_ALL } = TreeSelect;
import dictData from './config';
import { isZiGuanEvir } from '../../../utils/commonFunc';
import { formatDictData } from '../../../utils/utils';
import CardTreeListC from './cardTreeList';
import { T } from 'antd/lib/upload/utils';
const FormItem = Form.Item;

@Form.create()
class AddFenzi extends PureComponent {
  state = {
    controlValueType: 1, //控制类别显示的是什么 0:是否下拉，1:树形下拉 ，2:输入框
    cLeveType: '',
    components: [], //公式下面的 关系公式 树形结构
    Factor: [], //计算因子下拉
    conditionBoundList: [], //证券类型下拉
    conditionOrigin: [], //证券类型原始数据
    controlValuesList: [], //控制类别下拉数据
    compareMethodList: [], //比较方向下拉
    RiskIndexInfo: [],
    currentNode: undefined, //点击树节点 存储节点的数据
    showTemplate: false, //展示模板名称编辑弹窗
    templateObj: undefined, //当前正在保存的模板
    templatelist: [], //模板下拉
    currentTemp: undefined, //当前选择的模板名称
  };

  componentDidMount() {
    const { dispatch, detailData = {} } = this.props;
    this.searchFactorAndCondition(detailData.indexCatcode || '-1'); //默认指标分类 全部  查询证券类型 和 计算因子
    this.setState({
      components: detailData.conditionList || [],
    });
    //查询模板列表
    this.queryTemplateList();
  }

  //查询计算因子、证券类型下拉 清空计算因子和证券类型  flag回填时调用
  searchFactorAndCondition = (value, id) => {
    const { dispatch } = this.props;
    const { resetFields } = this.props.form;
    const that = this;
    // if(this.state.currentNode) this.setState({currentNode:undefined});//指标分类切换之后 不可保存 可新建
    if (!id) resetFields(['riskFactorNo', 'controlValue', 'conditionBoundNo', 'compareMethod']);
    this.setState({
      conditionList: {},
    });
    dispatch({
      type: 'limitManagemen/queryFactorByIndexClass',
      payload: {
        indexCateCode: value,
      },
    }).then((res) => {
      if (res && res.success) {
        let arr = [];
        if (res.data) {
          arr = res.data.map((item) => {
            return {
              title: `${item.riskFactorName}-${item.factorBeanName}`,
              value: item.riskFactorNo.toString(),
            };
          });
        }
        that.setState({
          Factor: [...arr],
        });
      }
    });
    //获取证券类型下拉
    dispatch({
      type: 'limitManagemen/queryConditionByIndexClass',
      payload: {
        indexCateCode: value,
      },
    }).then((res) => {
      if (res && res.success) {
        let arr = [];
        if (res.data) {
          arr = res.data.map((item) => {
            return {
              title: item.boundName,
              value: item.boundNo.toString(),
            };
          });
        }
        //查询证券类型下拉
        that.setState({
          conditionOrigin: res.data || [],
          conditionBoundList: arr,
        });
        if (id) {
          //公式回填查询数据
          this.onChangeCondition(id, 'type');
        }
      }
    });
  };
  //确定 保存在前台数据
  onOK = (type) => {
    const { validateFields } = this.props.form;
    let query;
    validateFields(['indexName', 'riskFactorNo', 'operateMode', 'indexCatcode'], (err, values) => {
      if (!err) {
        const params = {
          ...values,
          indexId: this.props.detailData ? this.props.detailData.indexId : new Date().getTime(),
          ctrlType: this.props.indexType, //分子1还是分母2
          indexSeq: Number(1), //无法知道含义
          operateMode: Number(values.operateMode),
          riskFactorNo: Number(values.riskFactorNo),
          tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant'),
        };

        let conditionList = this.state.TreeList.state.components;
        params.conditionList = conditionList;
        if (type == 'template') {
          //模板保存的校验
          query = params;
        } else {
          this.props.onOK(params); //将当前分子数据传给父组件
        }
      } else {
        if (type == 'template') {
          //模板保存的校验
          message.warning('请检查必填项！');
        }
      }
    });
    return query;
  };
  //证券类型变更 清空 比较方向 控制类别
  onChangeCondition = (e, type) => {
    const { resetFields } = this.props.form;
    const { conditionOrigin } = this.state;
    if (!type) resetFields(['compareMethod', 'controlValue']);
    const arr = conditionOrigin.filter((item) => item.boundNo == e);
    if (arr.length) {
      //获取控制方向的下拉 以及控制类别的展示形式 及下拉
      this.setState({
        compareMethodList: arr[0].compareMethod == 0 ? dictData.directionList : dictData.directionList.filter((item) => item.value > 4),
        controlValueType: arr[0].controlValueType,
        controlValuesList: arr[0].controlValues,
      });
    } else {
      this.setState({
        compareMethodList: [],
        controlValueType: 1,
        controlValuesList: [],
      });
    }
  };
  //添加关系
  addRelation = () => {
    const {
      form: { getFieldsValue },
    } = this.props;
    const params = getFieldsValue(['joinTypeMode', 'controlValue', 'conditionBoundNo', 'compareMethod']);
    this.state.TreeList.addRelation(params); //调用子组件新增关系函数
  };
  //修改公式节点
  addExpression = (type) => {
    const {
      form: { validateFields },
    } = this.props;
    validateFields(['indexCatcode', 'joinTypeMode', 'controlValue', 'conditionBoundNo', 'compareMethod'], (err, values) => {
      if (!err) {
        console.log(values);
        if (type == 'add') this.state.TreeList.addExpression(values);
        if (type == 'edit') this.state.TreeList.editExpression(values);
      }
    });
  };
  //控制类别下拉 转化成树形结构
  changeTreeData = (data) => {
    let arr = [];
    data
      ? data.map((item) => {
          const newData = {};
          newData.title = item.itemDesc;
          newData.key = item.value;
          newData.value = item.value;
          newData.children = item.children ? this.changeTreeData(item.children) : '';
          arr.push(newData);
        })
      : null;
    return arr;
  };
  //模板切换 重新渲染分子的所有数据
  onChangeTemp = (e) => {
    const { templatelist } = this.state;
    if (e) {
      templatelist.map((item) => {
        if (item.value == e) {
          let obj = item.indexList ? item.indexList[0] : undefined;
          if (obj) this.setValue(obj);
          this.setState({
            currentTemp: { value: item.value, title: item.title },
          });
        }
      });
    } else {
      this.setState({
        currentTemp: undefined,
      });
    }
  };
  //渲染分子表单
  setValue = (obj) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    if (!obj) return;
    setFieldsValue({
      operateMode: obj.operateMode?.toString(),
      indexName: obj.indexName,
      riskFactorNo: obj.riskFactorNo?.toString(),
      indexCatcode: obj.indexCatcode,
    });
    this.setState({
      components: obj.conditionList || [],
    });
  };
  renderTopForm = () => {
    const {
      loading,
      form: { getFieldValue, getFieldDecorator },
      detailData = {},
      limitManagemen: { dictMap = {} },
    } = this.props;
    const { Factor, currentNode, conditionBoundList, compareMethodList, controlValuesList, controlValueType } = this.state;
    let treeData = [];
    if (controlValueType == 1) {
      treeData = this.changeTreeData(controlValuesList);
    }
    return (
      <div className={myStyle.topCls}>
        <div>
          <SelectC form={this.props.form} dataIndex='operateMode' title='符号' initialValue={detailData.operateMode || '1'} dataSource={dictData.shiftMethod} />
        </div>
        <div>
          <InputC
            form={this.props.form}
            dataIndex='indexName'
            title='指标名称'
            initialValue={detailData.indexName || undefined}
            rules={[{ required: true, message: '指标名称不能为空' }]}
          />
        </div>
        <div>
          <div>
            <SelectC
              form={this.props.form}
              dataIndex='templateId'
              title='模板选择'
              initialValue={detailData.templateId || undefined}
              dataSource={this.state.templatelist}
              allowClear={true}
              onChange={this.onChangeTemp}
              optionTitle={true}
            />
          </div>
          <div>
            <PrimaryGhostC title='保存' disabled={!getFieldValue('templateId') == true} onClick={() => this.saveTemplate('save')} />
            <PrimaryGhostC title='另存为' onClick={() => this.saveTemplate('saveAs')} />
            <Popconfirm
              title={'确定删除？'}
              icon={<ExclamationCircleOutlined />}
              onConfirm={() => {
                this.deleteTemplate();
              }}
            >
              <PrimaryGhostC disabled={!getFieldValue('templateId') == true} title='删除' loading={loading.effects['limitManagemen/deleteTemplate'] == true} />
            </Popconfirm>
          </div>
        </div>
        <div>
          <div>
            <SelectC
              form={this.props.form}
              dataIndex='riskFactorNo'
              title='计算因子'
              initialValue={detailData.riskFactorNo ? detailData.riskFactorNo.toString() : undefined}
              dataSource={Factor}
              optionTitle={true}
              rules={[{ required: true, message: '计算因子不能为空' }]}
            />
          </div>
        </div>
        <div>
          <div>
            <SelectC
              form={this.props.form}
              dataIndex='joinTypeMode'
              title='关联规则'
              initialValue={detailData.joinTypeMode ? detailData.joinTypeMode : '1'}
              dataSource={dictData.joinTypeMode}
            />
          </div>
          <div>
            <PrimaryC title='添加关系' onClick={this.addRelation} />
          </div>
        </div>
        <div>
          {/* 指标分类 */}
          <div>
            <SelectC
              form={this.props.form}
              dataIndex='indexCatcode'
              onChange={(e) => this.searchFactorAndCondition(e)}
              initialValue={detailData.indexCatcode ? detailData.indexCatcode : '-1'}
              dataSource={dictMap.index_category ? formatDictData(dictMap.index_category) : []}
              rules={[{ required: true, message: '指标分类必填' }]}
            />
          </div>
          <div>
            {/* 证券类型 */}
            <SelectC
              form={this.props.form}
              dataIndex='conditionBoundNo'
              dataSource={conditionBoundList || []}
              onChange={(e) => this.onChangeCondition(e)}
              disabled={getFieldValue('indexCatcode') == undefined}
              rules={[{ required: true, message: '证券类型必填' }]}
            />
          </div>
          {/* 比较方向  根据证券类型变化*/}
          <div>
            <SelectC
              form={this.props.form}
              dataIndex='compareMethod'
              initialValue={detailData.compareMethod !== undefined ? detailData.compareMethod.toString() : undefined}
              dataSource={compareMethodList}
              disabled={getFieldValue('conditionBoundNo') == undefined}
              rules={[{ required: true, message: '方向必填' }]}
            />
          </div>
          {/* 控制类别 */}
          <div>
            {controlValueType == 0 ? (
              <SelectC
                form={this.props.form}
                dataIndex='controlValue'
                initialValue={undefined}
                dataSource={controlValuesList.map((item) => {
                  return { title: item.itemName, value: item.value };
                })}
                disabled={getFieldValue('conditionBoundNo') == undefined}
                rules={[{ required: true, message: '控制类别必填' }]}
              />
            ) : null}
            {controlValueType == 1 ? (
              <TreeSelectC
                form={this.props.form} // form对象
                dataIndex='controlValue' // Form识别的Item ID
                dataSource={treeData}
                isMultiple={true}
                treeCheckable={true}
                treeDefaultExpandAll={true}
                showCheckedStrategy={SHOW_ALL}
                disabled={getFieldValue('conditionBoundNo') == undefined}
                rules={[{ required: true, message: '控制类别必填' }]}
              />
            ) : null}
            {controlValueType == 2 ? (
              <InputC
                form={this.props.form}
                dataIndex='controlValue'
                disabled={getFieldValue('conditionBoundNo') == undefined}
                rules={[{ required: true, message: '控制类别必填' }]}
              />
            ) : null}
          </div>
          <div>
            <PrimaryGhostC title='保存' disabled={currentNode ? false : true} onClick={() => this.addExpression('edit')} />
            <PrimaryC title='新建' onClick={() => this.addExpression('add')} />
          </div>
        </div>
      </div>
    );
  };

  //保存模板 直接保存至后端 无需点击确定按钮
  saveTemplate = (type) => {
    let query = this.onOK('template');
    if (!query) {
      message.warning('请填写完整');
      return;
    }
    this.setState(
      {
        templateObj: query,
      },
      () => {
        if (type == 'save') {
          //保存
          const params = {
            indexList: [this.state.templateObj],
            name: this.state.currentTemp.title,
            id: this.state.currentTemp.value,
            tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant'),
          };
          this.saveTemp(params, 'limitManagemen/editTemplate'); //保存至后端
        } else {
          //另存为
          this.setState({
            showTemplate: true,
          });
        }
      },
    );
  };
  //删除模板
  deleteTemplate = () => {
    const {
      form: { getFieldValue, setFieldsValue },
      dispatch,
    } = this.props;
    dispatch({
      type: 'limitManagemen/deleteTemplate',
      payload: { id: getFieldValue('templateId') },
      callback: () => {
        this.queryTemplateList(); //重新查询下拉并定位到对应数据
        setFieldsValue({
          templateId: undefined,
        });
        this.setState({ currentTemp: undefined });
      },
    });
  };
  //查询模板列表
  queryTemplateList = () => {
    const {
      form: { getFieldValue },
      dispatch,
    } = this.props;
    dispatch({
      type: 'limitManagemen/queryTemplateList',
      payload: { tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant') },
      callback: (data) => {
        this.setState({
          templatelist: data || [],
        });
      },
    });
  };
  //关系 公式列表展示
  renderBottomList = () => {
    return <div className={myStyle.bottomList}>列表</div>;
  };
  //获取到回填form公式数据
  getCurrentNode = (obj) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.props;
    console.log(obj, '当前node');

    if (!obj) {
      this.setState({ currentNode: obj });
      return; //无选中子节点
    }
    if (obj && obj.conditionBoundNo == '') return; //证券类型未选
    this.setState(
      {
        currentNode: obj,
        controlValueType: obj.controlValueType,
      },
      () => {
        if (obj.indexCatcode != getFieldValue('indexCatcode')) this.searchFactorAndCondition('-1', obj.conditionBoundNo.toString());
        else if (obj.conditionBoundNo != getFieldValue('conditionBoundNo')) {
          this.onChangeCondition(obj.conditionBoundNo, 'type');
        }
        setFieldsValue({
          indexCatcode: '-1',
          joinTypeMode: obj.joinTypeMode.toString(),
          conditionBoundNo: obj.conditionBoundNo ? obj.conditionBoundNo.toString() : obj.conditionBoundNo,
          compareMethod: obj.compareMethod.toString(),
          controlValue: obj.controlValue ? obj.controlValue : undefined,
        });
      },
    );
  };
  //保存名称即新增
  saveTemplateName = () => {
    const { validateFields } = this.props.form;
    validateFields(['templateName'], (err, values) => {
      if (!err) {
        if (!this.state.templateObj) return;
        const params = {
          indexList: [this.state.templateObj],
          name: values.templateName,
          tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant'),
        };
        this.saveTemp(params, 'limitManagemen/addTemplate'); //保存至后端
      }
    });
  };
  //模板保存至后端
  saveTemp = (params, url) => {
    this.props.dispatch({
      type: url,
      payload: {
        ...params,
      },
      callback: () => {
        this.setState({
          showTemplate: false,
        });
        this.queryTemplateList(); //重新查询下拉并定位到对应数据
      },
    });
  };
  //取消模板名称的保存
  cancelTemplate = () => {
    this.setState({
      showTemplate: false,
    });
  };
  render() {
    const { detailData, visible, indexType, loading } = this.props;
    let title = indexType == '1' ? '分子' : '分母';
    const modalProps = {
      visible: visible,
      onOk: this.onOK,
      onCancel: () => {
        this.props.onCancel();
      },
      title: detailData ? `${title}设置-编辑` : `${title}设置-新增`,
      className: myStyle.AddFenzi,
      width: 1000,
    };
    const modalTemplateProps = {
      visible: this.state.showTemplate,
      onOk: this.saveTemplateName,
      onCancel: this.cancelTemplate,
      title: '另存为',
      height: 50,
      width: 380,
      confirmLoading: loading.effects['limitManagemen/addTemplate'] == true || loading.effects['limitManagemen/editTemplate'] == true,
    };
    return (
      <ModalC {...modalProps}>
        {this.renderTopForm()}
        <CardTreeListC
          onRef={(ref) => {
            this.setState({ TreeList: ref });
          }}
          data={this.state.components}
          conditionOrigin={this.state.conditionOrigin}
          getCurrentNode={this.getCurrentNode}
        />
        {this.state.showTemplate && (
          <ModalC {...modalTemplateProps}>
            <div className={myStyle.templateName}>
              <InputC form={this.props.form} dataIndex='templateName' title='模板名称' initialValue={undefined} rules={[{ required: true, message: '模板名称不能为空' }]} />
            </div>
          </ModalC>
        )}
      </ModalC>
    );
  }
}
export default connect(({ limitManagemen, dictionaryM, userM: user, loading }) => ({
  limitManagemen,
  dictionaryM,
  user,
  loading,
}))(AddFenzi);
